var AOS = {
    init: function(e) {
        var allAos = document.querySelectorAll('*[aos]')
        for (let i = 0; i < allAos.length; i++) {
            document.body.clientWidth > e.mobile ? perform() : execution()
            function perform() {
                allAos[i].classList.add('aos-init')
                var offset = allAos[i].getBoundingClientRect().top - document.documentElement.clientHeight + 150
                if (offset < 0) {
                    allAos[i].classList.add('aos-animate')
                } else if (e.once !== true){
                    allAos[i].classList.remove('aos-animate')
                }
            }
            function execution() {
                allAos[i].removeAttribute('aos')
                allAos[i].removeAttribute('aos-delay')
            }
        }
    }
}

$(document).on('click','body', function () {
    $('.down_pull .on').removeClass('on')
})

const countItems = document.querySelectorAll('.count-item');
function onIntersection(entries, observer) {
    entries.forEach(entry => {
        if (entry.isIntersecting) {
            const e = entry.target;
            animateCount(e);
            // observer.unobserve(e);
        }
    });
}
const observer = new IntersectionObserver(onIntersection);
countItems.forEach(item => observer.observe(item));
function animateCount(e) {
    var demo = { score: 0 },
        scoreDisplay = e,
        to = e.getAttribute('data-to'),
        speed = e.getAttribute('data-speed') * 1,
        separator = e.getAttribute('data-separator'),
        to_fixed = e.getAttribute('data-fixed');

    if (to !== null) {
        if (to.indexOf('.') !== -1) {
            var automatic = (to.length -1)-to.indexOf('.')
        }
    }
    if (speed === 0) {
        speed = 1;
    }
    TweenLite.to(demo, speed, {
        score: to,
        onUpdate: showScore
    });
    function showScore() {
        if (separator !== null) {
            scoreDisplay.innerHTML = formatNumberWithCommasAndDecimal(demo.score, to_fixed, separator);
        }else if (to_fixed !== null) {
            scoreDisplay.innerHTML = demo.score.toFixed(automatic);
        }else {
            scoreDisplay.innerHTML = demo.score.toFixed(0);
        }
    }
}
function formatNumberWithCommasAndDecimal(number, decimalPlaces,separator) {
    var formattedNumber = number.toFixed(decimalPlaces);
    formattedNumber = formattedNumber.replace(/\B(?=(\d{3})+(?!\d))/g, separator);
    return formattedNumber;
}


$('video:not(video[muted])').trigger('pause')

function video_alert(e) {
    var alert = $('.alert_video')
    var video = $('.alert_video .joke .video video')
    var controls = $(e).find('video').attr('controls')
    var loop = $(e).find('video').attr('loop')
    $(video).attr('controls',controls)
    $(video).attr('loop',loop)
    $(alert).addClass('video_active')
    $(video).attr('src',$(e).find('video').attr('src'))
    $(video).trigger('play');
    if ($(e).is('.all')) {
        $(alert).addClass('all')
    }else {
        $(alert).removeClass('all')
    }
}

function video_close() {
    $('.alert_video').removeClass('video_active')
    $('.alert_video .joke .video video').trigger('pause');
    $('.alert_video .joke .item').removeClass('item_active')
}

$(document).on('click','.alert_video .joke .close',function () {
    video_close()
})

$(document).on('click','.alert_video .mask',function () {
    video_close()
})

var video_html = '';
video_html+= `<div class="alert_video">
    <div class="joke">
        <div class="video">
            <video src=""></video>
        </div>
        <div class="close">
            <svg t="1676432369827" class="icon" viewBox="0 0 1024 1024" version="1.1" xmlns="http://www.w3.org/2000/svg"
                 p-id="2743" width="64" height="64">
                <path d="M548.992 503.744L885.44 167.328a31.968 31.968 0 1 0-45.248-45.248L503.744 458.496 167.328 122.08a31.968 31.968 0 1 0-45.248 45.248l336.416 336.416L122.08 840.16a31.968 31.968 0 1 0 45.248 45.248l336.416-336.416L840.16 885.44a31.968 31.968 0 1 0 45.248-45.248L548.992 503.744z"
                      p-id="2744"></path>
            </svg>
        </div>
    </div>
    <div class="mask"></div>
</div>`

if ($('*[onclick*="video_alert(this)"] video').length > 0) {
    $('body').append(video_html)
}

function on(t,s) {
    $(t).addClass('on').siblings().removeClass('on')
    $(s).removeClass('on').eq($(t).index()).addClass('on')
}

function log(t) {
    console.log(t)
}

function logLength(t) {
    console.log(t[0].getTotalLength())
}

document.querySelectorAll('[data-wheel]').forEach(function(element) {
    element.addEventListener('wheel', function(e) {
        e.stopPropagation();
    });
});


$('.text_effect').each(function (index,ele) {
    var ly = $(ele).data('delay');
    if (ly === undefined) {
        ly = 20;
    }
    var text = $(ele).find('.appoint').text();
    var html = '';
    for(var i=0;i<text.length;i++){
        html += '<div style="display: inline-block;">'+text[i]+'</div>';
    }
    $(ele).find('.appoint').html('<div class="fist">'+html+'</div> <div class="fist">'+html+'</div>');
    $(ele).find('.fist').each(function (i,e) {
        $(e).find('div').each(function (i,e) {
            var delay = i*ly;
            $(e).css({
                'transition': '0.6s cubic-bezier(0.76, 0, 0.24, 1) '+ delay +'ms'
            })
        })
    })
})

// text_effect2 start
const DOM = {};
var domDelay = 180;
DOM.enter = document.querySelectorAll('.text_effect2 .appoint');
for (let i = 0; i < DOM.enter.length; i++) {
    function rgbToHex(rgb) {
        var rgbValues = rgb.match(/\d+/g);
        var hexColor = '#' + rgbValues.map(function (value) {
            var hex = parseInt(value).toString(16);
            return hex.length === 1 ? '0' + hex : hex;
        }).join('');
        return hexColor;
    }

    DOM.enter.forEach(element => {
        const text = element.textContent;
        element.innerHTML = '';

        for (const char of text) {
            const charSpan = document.createElement('span');
            charSpan.textContent = char;
            element.appendChild(charSpan);
        }
    });

    DOM.enter[i].addEventListener('mouseenter', function () {
        var span = DOM.enter[i].querySelectorAll('span');
        var data_color = DOM.enter[i].getAttribute('data-color')
        anime.remove(span);
        anime({
            targets: span,
            delay: (t, i) => i * 20,
            translateY: [
                {value: 10, duration: domDelay, easing: 'easeInQuad'},
                {value: [-10, 0], duration: domDelay, easing: 'easeOutQuad'}
            ],
            opacity: [
                {value: 0, duration: domDelay, easing: 'linear'},
                {value: 1, duration: domDelay, easing: 'linear'}
            ],
            color: {
                value: data_color,
                duration: 1,
                delay: (t, i, l) => i * 20 + 150
            }
        });
    });

    DOM.enter[i].addEventListener('mouseleave', function () {
        var span = DOM.enter[i].querySelectorAll('span');
        var color_ = window.getComputedStyle(DOM.enter[i]).color;
        var hexColor = rgbToHex(color_);
        anime.remove(span);
        anime({
            targets: span,
            delay: (t, i, l) => (l - i - 1) * 20,
            translateY: [
                {value: 10, duration: domDelay, easing: 'easeInQuad'},
                {value: [-10, 0], duration: domDelay, easing: 'easeOutQuad'}
            ],
            opacity: [
                {value: 0, duration: domDelay, easing: 'linear'},
                {value: 1, duration: domDelay, easing: 'linear'}
            ],
            color: {
                value: hexColor,
                duration: 1,
                delay: (t, i, l) => (l - i - 1) * 20 + 150
            }
        });
    });
}

// text_effect2 end

var magnets = document.querySelectorAll('.hover_button')
for (let i = 0; i < magnets.length; i++) {
    var speed = magnets[i].getAttribute('data-speed')
    if (!speed) {
        speed = 20
    }
    var strength = speed
}


magnets.forEach( (magnet) => {
    magnet.addEventListener('mousemove', moveMagnet );
    magnet.addEventListener('mouseout', function(event) {
        TweenMax.to( event.currentTarget, 1, {x: 0, y: 0, ease: Power4.easeOut})
    } );
});

function moveMagnet(event) {
    var magnetButton = event.currentTarget
    var bounding = magnetButton.getBoundingClientRect()

    TweenMax.to( magnetButton, 1, {
        x: ((( event.clientX - bounding.left)/magnetButton.offsetWidth) - 0.5) * strength,
        y: ((( event.clientY - bounding.top)/magnetButton.offsetHeight) - 0.5) * strength,
        ease: Power4.easeOut
    })
}


let d = document.querySelector(".cursor")
if (d) {
    let speed = document.querySelector('.cursor').getAttribute('data-speed')
    if (speed === null) {
        speed = 0.9
    }else {
        speed = speed / 10
    }
    function S() {
        d && function (e) {
            gsap.set(e, {
                xPercent: -50,
                yPercent: -50
            });
            let t = e,
                r = {
                    x: window.innerWidth / 2,
                    y: window.innerHeight / 2
                },
                o = {
                    x: r.x,
                    y: r.y
                },
                a = gsap.quickSetter(t, "x", "px"),
                n = gsap.quickSetter(t, "y", "px");
            document.body.addEventListener("mousemove", e => {
                o.x = e.x, o.y = e.y
            }), gsap.ticker.add(() => {
                const e = 1 - Math.pow(speed, gsap.ticker.deltaRatio());
                r.x += (o.x - r.x) * e, r.y += (o.y - r.y) * e, a(r.x), n(r.y)
            })
        }(d)
    }
    window.addEventListener("DOMContentLoaded", () => {
        S();
    })
}

var down_pull = document.querySelectorAll('.down_pull')
for (let i = 0; i < down_pull.length; i++) {
    down_pull[i].addEventListener('click', function (e) {
        e.stopPropagation();
        for (let j = 0; j < down_pull.length; j++) {
            if (down_pull[j] !== this) {
                down_pull[j].querySelector('.pull').classList.remove('on');
            }
        }
        this.querySelector('.pull').classList.toggle('on');
    });

    var p = down_pull[i].querySelectorAll('.pull p')
    for (let j = 0; j < p.length; j++) {
        p[j].addEventListener('click',function () {
            var txt = down_pull[i].querySelector('.txt')
            txt.innerHTML = this.innerHTML
            var sib = this.parentNode.children
            for (let k = 0; k < sib.length; k++) {
                sib[k].classList.remove('on')
            }
            this.classList.add('on')
        })
    }
}

const Pull = {
    init({ scrollTop, trigger }) {
        let clientHeight = document.documentElement.clientHeight;

        trigger.forEach(({ el, el_start, auto, nostop , x, y, z, scale, opacity, borderRadius, distance, animate, ease}) => {
            distance === undefined ? distance = 0 : distance
            let data_view = $(el_start),
                startPosition = data_view.position().top + distance,
                t = (scrollTop - startPosition) / animate,
                x_start,
                y_start,
                z_start,
                scale_start,
                opacity_start,
                borderRadius_start

            x = getUndefined(x)
            y = getUndefined(y)
            z = getUndefined(z)

            scale === undefined ? scale = [1,1] : scale

            x_start = getStart(x,ease)
            y_start = getStart(y,ease)
            z_start = getStart(z,ease)
            scale_start = getStart(scale,ease)
            opacity_start = getStart(opacity,ease)
            borderRadius_start = getStart(borderRadius,ease)

            function getStart(q,ease){
                if (q) {
                    return q[0] + (ease ? easeOutQuad(t) :t) * (q[1]-q[0])
                }
            }

            function getUndefined(i) {
                return i === undefined ? i = [0,0] : i
            }

            function acquiesce() {
                if (scrollTop >= startPosition) {
                    $(el).css({
                        'transform': `translate3d(${x_start}px, ${y_start}px, ${z_start}px) scale(${scale_start})`,
                    });
                    if (borderRadius) {
                        $(el).css({
                            'border-radius': `${borderRadius_start}px`,
                        });
                    }
                    if (opacity) {
                        $(el).css({
                            'opacity' : opacity_start
                        });
                    }
                } else if (scrollTop <= startPosition + distance) {
                    $(el).css({
                        'transform': `translate3d(${x[0]}px, ${y[0]}px, ${z[0]}px) scale(${scale[0]})`,
                    });
                    if (borderRadius) {
                        $(el).css({
                            'border-radius': `${borderRadius[0]}px`,
                        });
                    }
                    if (opacity) {
                        $(el).css({
                            'opacity' : opacity[0]
                        });
                    }
                }

                if (scrollTop >= startPosition + animate) {
                    $(el).css({
                        'transform': `translate3d(${x[1]}px, ${y[1]}px, ${z[1]}px) scale(${scale[1]})`,
                    });
                    if (borderRadius) {
                        $(el).css({
                            'border-radius': `${borderRadius[1]}px`,
                        });
                    }
                    if (opacity) {
                        $(el).css({
                            'opacity' : opacity[1]
                        });
                    }
                }
            }

            function addition() {
                let y = scrollTop - data_view.position().top;
                let y_end = data_view.height() - clientHeight;

                if (!nostop) {
                    y = Math.min(y, y_end);
                }

                let translateY = scrollTop >= data_view.position().top ? y : '0';
                $(el).css({'transform': 'translate3d(0, '+ translateY +'px, 0)'});
            }

            !auto ? acquiesce() : addition()
        });
    }
};

function easeOutQuad(t) {
    return t * (2 - t);
}

